<?php

namespace App\Console\Commands;

use App\Models\Config;
use App\Models\UserSecret;
use App\Services\WechatService;
use App\Utils\Code;
use Illuminate\Console\Command;

class MigrateCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'migrate:wechat {app:迁移应用 gzh-微信公众号用户迁移}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * @throws \Exception
     */
    public function handle()
    {
        $wechat = new WechatService();
        $response = $wechat->gzhUserList();
        if (isset($response['errcode']) && $response['errcode'] > 0) {
            echo "Error 【{$response['errcode']}】".$response['errmsg'] . PHP_EOL;
        }
        $config = Config::where('key', 'wechat_gzh')->first()->toArray();
        if (!$config['value'] || !isset($config['params']['secret']) || !$config['params']['secret']) {
            throw new \Exception('公众号通讯参数未配置', Code::LACK_OF_CONDITIONS);
        }
        $lack = 0;
        foreach ($response['data']['openid'] as $i => $openid) {
            $userInfo = $wechat->gzhUserInfo($openid, $config);
            if (!$secret = UserSecret::where('mode', 'wx_gzh')->where('secret', $openid)->first()) {
                $secret = new UserSecret();
                $secret->mode = 'wx_gzh';
                $secret->secret = $openid;
            };
            if (isset($userInfo['unionid']) && $userInfo['unionid']) {
                $secret->unionid = $userInfo['unionid'];
                if (!$secret->user_id && ($userId = \DB::table('user_secrets')
                        ->where('unionid', $secret->unionid)->whereNotNull('user_id')->value('user_id'))) {
                    $secret->user_id = $userId;
                } elseif ($secret->user_id && \DB::table('user_secrets')
                        ->where('unionid', $secret->unionid)->whereNull('user_id')->exists()) {
                    \DB::table('user_secrets')
                        ->where('unionid', $secret->unionid)->whereNull('user_id')->update(['user_id', $secret->user_id]);
                }
            } else {
                $lack++;
                echo PHP_EOL . "【{$userInfo['nickname']}】-{$openid} 该用户没有 unionid 信息" . PHP_EOL;
            }
            $secret->is_keep = 1;
            $secret->save();
            echo '.';
        }
        $success = PHP_EOL . '进度 100% - 数据迁移成功';
        if ($lack > 0) {
            $success .= " 其中有{$lack}位用户没有 unionid 信息";
        }
        echo $success;
    }
}
